package com.jieshuibao.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.ImagesRequest;
import com.jieshuibao.model.domain.ImagesResponse;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.util.Base64ForImg;

@Controller
public class ImageController {
	private static final Logger logger = LoggerFactory
			.getLogger("ImageController.class");

	private static final ObjectMapper mapper = new ObjectMapper();

	@Value("${question.images.path}")
	private String questionImagesPath;

	@Value("${images.basePath}")
	private String imagesBasePath;

	@Resource
	private RedisService redisService;

	@RequestMapping(value = "/question/getImages", method = RequestMethod.POST)
	@ResponseBody
	public Object pageList(HttpServletRequest request,
			@RequestBody ImagesRequest imagesRequest) {
		ImagesResponse imagesResponse = new ImagesResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(imagesRequest));

			List<String> imageNames = imagesRequest.getImageNames();
			String cookieId = request.getHeader("cookieId");
			if (null != cookieId) {
				if (null != imageNames && imageNames.size() > 0) {
					imagesResponse.setCode("1");
					List<String> images = new ArrayList<String>();
					for (String imageName : imageNames) {
						String imageStr = Base64ForImg
								.GetImageStr(questionImagesPath + imageName);
						if (!imageStr.equals("")) {
							images.add(imageStr);
						}
					}
					if (images.size() > 0) {
						imagesResponse.setImages(images);
					} else {
						imagesResponse.setCode("3");
						imagesResponse.setDes("图片获取失败");
					}
				} else {
					imagesResponse.setCode("3");
					imagesResponse.setDes("请求图片列表为空");
				}
			} else {
				imagesResponse.setCode("2");
				imagesResponse.setDes("请重新登录");
			}
			logger.info("返回：" + mapper.writeValueAsString(imagesResponse));

		} catch (Exception e) {
			imagesResponse.setCode("0");
			imagesResponse.setDes("系统繁忙");
			e.printStackTrace();
		}
		return imagesResponse;
	}

	@RequestMapping(value = "/showImage/{path}/{name}")
	public void showImage(HttpServletRequest request,
			HttpServletResponse response,
			@PathVariable(value = "path") String path,
			@PathVariable(value = "name") String name) {
		String cookieId = request.getHeader("cookieId");
		if (cookieId != null) {
			//String phoneNum = redisService.get(cookieId);
			CookieUser cookieUser = redisService.getObejct(cookieId, CookieUser.class);
			String phoneNum = cookieUser.getPhoneNumber();
			if (phoneNum != null) {
				response.setContentType("text/html; charset=UTF-8");
				response.setContentType("image/jpeg");
				String imagePath = imagesBasePath + path + "/" + name;
				if(name!=null&&!name.equals("")){
					FileInputStream fis = null;
					OutputStream os = null;
					try {
						fis = new FileInputStream(imagePath);
						os = response.getOutputStream();
						int count = 0;
						byte[] buffer = new byte[1024 * 1024];
						while ((count = fis.read(buffer)) != -1)
							os.write(buffer, 0, count);
						os.flush();
					} catch (IOException e) {
						logger.info("图片" +imagePath+"不存在");

					} finally {
						if (os != null)
							try {
								os.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						if (fis != null)
							try {
								fis.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
					}
				
				}
		}
		}

	}
	
	@RequestMapping(value = "/showImg/{path}/{name}")
	public void showImg(HttpServletRequest request,
			HttpServletResponse response,
			@PathVariable(value = "path") String path,
			@PathVariable(value = "name") String name) {
				response.setContentType("text/html; charset=UTF-8");
				response.setContentType("image/jpeg");
				String imagePath = imagesBasePath + path + "/" + name;
				if(name!=null&&!name.equals("")){
					FileInputStream fis = null;
					OutputStream os = null;
					try {
						fis = new FileInputStream(imagePath);
						os = response.getOutputStream();
						int count = 0;
						byte[] buffer = new byte[1024 * 1024];
						while ((count = fis.read(buffer)) != -1)
							os.write(buffer, 0, count);
						os.flush();
					} catch (IOException e) {
						logger.info("图片" +imagePath+"不存在");
					} finally {
						if (os != null)
							try {
								os.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
						if (fis != null)
							try {
								fis.close();
							} catch (IOException e) {
								e.printStackTrace();
							}
					}
				
				}
		
		}

}
